What is string-length?
The string-length npm package is used to get the real length of a string, taking into account Unicode characters and ansi escape codes that might be present in the string. It provides a more accurate count of visual symbols in a string, which can be different from the string's `.length` property due to such characters.
What are string-length's main functionalities?
Counting characters in a basic string
This feature allows you to count the number of characters in a basic string, which is straightforward and similar to the native JavaScript `.length` property, but it also correctly handles Unicode characters that are represented by surrogate pairs in JavaScript.
"string-length": "^4.0.1"
Counting characters in a string with Unicode
This feature is particularly useful for strings containing Unicode characters, such as emojis or characters from non-Latin scripts, which may be represented by multiple code units in JavaScript. The `string-length` package accurately counts these as single characters.
"string-length": "^4.0.1"
Counting characters in a string with ansi escape codes
When dealing with strings that include ansi escape codes, such as those used for coloring terminal output, `string-length` can correctly count the visible characters, ignoring the escape codes that do not contribute to the visible length of the string.
"string-length": "^4.0.1"
Other packages similar to string-length
string-width
The `string-width` package is similar to `string-length` in that it calculates the visual width of a string in the terminal, considering Unicode and ansi escape codes. It is useful for aligning output in the terminal or for determining how much visual space a string will take up.
strip-ansi
While `strip-ansi` does not directly calculate string length, it is related in that it removes ansi escape codes from a string. This can be used in conjunction with the native `.length` property to determine the visual length of a string that contains such codes.
string-length
Get the real length of a string - by correctly counting astral symbols and ignoring ansi escape codes
String#length
errornously counts astral symbols as two characters.
Install
$ npm install string-length
Usage
const stringLength = require('string-length');
'🐴'.length;
stringLength('🐴');
stringLength('\u001B[1municorn\u001B[22m');
Related
License
MIT © Sindre Sorhus